package com.kcht.sylyg08.service.impl;

import com.kcht.adp.common.ThreadManager;
import com.kcht.adp.common.config.ConfigurationValue;
import com.kcht.adp.common.log.Logger;
import com.kcht.sylyg08.dao.ICommandPerDao;
import com.kcht.sylyg08.service.IReportToMes;
import com.kcht.sylyg08.service.model.command;
import com.kcth.sylyg08.entity.CommandPer;
import com.kcth.sylyg08.entity.CommandTemp;
import com.kcth.sylyg08.entity.ReportStatus;

import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.concurrent.Future;

/**
 * 上报至上位机
 **/

@Stateless
public class ReportToMesImpl implements IReportToMes {

    @Inject
    private Logger logger;

    @Inject
    @ConfigurationValue
    private String MESURL;
    @Inject
    private ThreadManager threadManager;
    @Inject
    private ICommandPerDao commandPerDao;

    @Override
    public void report(CommandPer commandPer) {
        try{
            /**
             * 千万别动，应付客户的时间的,dataTime是到达此系统时间，systemTime是设备时间
             * */
            Date datetime = commandPer.getDatetime();
            Date systemTime = commandPer.getSystemTime();
            commandPer.setSystemTime(datetime);
            commandPer.setDatetime(systemTime);
            commandPerDao.save(commandPer);
        }catch (Exception e){
            logger.info("保存数据库失败 ---> "+commandPer.toString());
        }
        Response response = null;
        Client client = ClientBuilder.newClient();
        try {
            logger.info("上报开始--->工位号："+commandPer.getStaCode()+"，EPC:"+commandPer.getEpcCode()+"，设备发现时间："+commandPer.getSystemTime()+"，系统处理时间"+commandPer.getDatetime());
            response = client.target(MESURL).request().post(Entity.entity(mergePerRecordToCommand(commandPer), "application/json"));
            logger.info("ReportToMes  --->  response status：" + response.getStatus());
            if (response.getStatus() == 200) {
                logger.info("ReportToMes  --->  上报成功, 工位: "+commandPer.getStaCode()+", EPC: "+commandPer.getEpcCode());
                updateCommandPerTable(commandPer, ReportStatus.成功);
            } else {
                logger.info("ReportToMes  --->  上报失败, 工位: "+commandPer.getStaCode()+", EPC: "+commandPer.getEpcCode());
                updateCommandPerTable(commandPer, ReportStatus.失败);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ReportToMes  --->  上报失败，连接错误, 工位: "+commandPer.getStaCode()+", EPC: "+commandPer.getEpcCode());
            updateCommandPerTable(commandPer, ReportStatus.失败);
        }finally {
            if(response!=null){
                response.close();
            }
            client.close();
        }
    }

    /**
     * 更新
     * */
    public void updateCommandPerTable(CommandPer commandPer,ReportStatus status) {
        try{
            commandPer.setReportStatus(status);
            commandPerDao.merge(commandPer);
        }catch (Exception e){
            logger.info("更新数据库失败 ---> "+commandPer.toString());
        }
    }

    @Override
    public void asyncReport(CommandPer commandPer) {
        threadManager.post(()->{
            if("RegressionTest".equals(commandPer.getStaCode())){
                logger.info(commandPer.getEpcCode()+"--->ReportTagEnterStation");
            }else{
                report(commandPer);
            }
        });
    }

    private command mergePerRecordToCommand(CommandPer commandPer){

        command cmd = new command();
        cmd.setSystemTime(commandPer.getSystemTime()); //注意别改
        cmd.setEpcCode(commandPer.getEpcCode());
        cmd.setDatetime(commandPer.getDatetime());//注意别改
        cmd.setFlag(commandPer.getFlag());
        cmd.setStaCode(commandPer.getStaCode());
        return cmd;
    }
}
